package com.workhours.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.workhours.dto.TripStartRequest;
import com.workhours.entity.RestRecord;
import com.workhours.entity.User;
import com.workhours.mapper.RestRecordMapper;
import com.workhours.mapper.UserMapper;
import com.workhours.vo.UserStatusResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务类
 *
 * @author WorkHours
 * @since 2025-09-19
 */
@Service
public class UserService {
    
    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RestRecordMapper restRecordMapper;
    
    @Autowired
    private AuthService authService;
    
    /**
     * 获取用户状态信息
     *
     * @return 用户状态
     */
    public UserStatusResponse getUserStatus() {
        Long userId = authService.getCurrentUserId();
        log.info("获取用户状态，userId: {}", userId);
        
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 获取用户的休息记录
        QueryWrapper<RestRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .orderByAsc("start_date");
        List<RestRecord> restRecords = restRecordMapper.selectList(queryWrapper);
        
        // 转换为VO
        List<UserStatusResponse.RestRecordVO> restRecordVOs = restRecords.stream()
                .map(UserStatusResponse.RestRecordVO::new)
                .collect(Collectors.toList());
        
        log.info("用户状态获取成功，出差开始日期: {}, 休息记录数量: {}", user.getTripStartDate(), restRecordVOs.size());
        
        return new UserStatusResponse(user.getTripStartDate(), restRecordVOs);
    }
    
    /**
     * 设置出差开始日期
     *
     * @param request 出差开始日期请求
     */
    public void setTripStartDate(TripStartRequest request) {
        Long userId = authService.getCurrentUserId();
        LocalDate startDate = request.getStartDate();
        
        log.info("设置出差开始日期，userId: {}, startDate: {}", userId, startDate);
        
        // 验证日期不能是未来日期
        if (startDate.isAfter(LocalDate.now())) {
            throw new RuntimeException("出差开始日期不能是未来日期");
        }
        
        // 更新用户的出差开始日期
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId)
                    .set("trip_start_date", startDate);
        
        int result = userMapper.update(null, updateWrapper);
        if (result <= 0) {
            throw new RuntimeException("更新出差开始日期失败");
        }
        
        log.info("出差开始日期设置成功，userId: {}, startDate: {}", userId, startDate);
    }
    
    /**
     * 获取用户信息
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    public User getUserById(Long userId) {
        return userMapper.selectById(userId);
    }
}
